package logic

import (
	"context"
	"fmt"
	"shop/model/cache"
	"shop/model/mysql"

	"shop/shoprpc/internal/svc"
	"shop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CardAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCardAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CardAddLogic {
	return &CardAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CardAddLogic) CardAdd(in *shoprpc.CardAddRequest) (*shoprpc.CardAddResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	data, _ := user.FindUserId(mysql.Db, in.UserId)
	if data.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	var product mysql.Product
	date, _ := product.FindProductId(mysql.Db, in.ProductId)
	if date.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	if in.Number > product.Stock {
		return nil, fmt.Errorf("商品库存不足")
	}
	key := fmt.Sprintf("card:%d:%d", in.UserId, in.ProductId)
	result, _ := cache.Rdb.Exists(l.ctx, key).Result()
	if result == 0 {
		m := map[string]interface{}{
			"userId":    in.UserId,
			"productId": in.ProductId,
			"number":    in.Number,
			"image":     product.Image,
			"title":     product.Title,
			"price":     product.Price,
			"stock":     product.Stock,
			"summit":    product.Summit,
		}
		cache.Rdb.HMSet(l.ctx, key, m)
	} else {
		cache.Rdb.HIncrBy(l.ctx, key, "number", in.Number)
	}

	return &shoprpc.CardAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
